import { useState } from 'react';
import { Form, Input, Button, App } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import loadable from '@loadable/component';
import { useDispatch } from 'react-redux';

import { registerByEmail } from '@/service/api';
import { HOME } from '@/config/url';
import { isRegEmail } from '@/utils';
import { setStore } from '@/reducers/common';

import styles from './index.module.scss';

const IconFont = loadable(() => import('@/components/IconFont'));

export default () => {
    const [submitting, setSubmitting] = useState(false);
    const { message } = App.useApp();
    const navigate = useNavigate();
    const dispatch = useDispatch();

    const onFinish = async (values) => {
        message.destroy();
        setSubmitting(true);

        try {
            const [res, err] = await registerByEmail(values);
            if(err) return message.error(err?.message || '注册失败');
            message.success('注册成功');
            const {token, user: userInfo} = res?.data || {};

            // 设置token等信息后再跳转
            localStorage.setItem('accessToken', token);
            localStorage.removeItem('inviter_code');
            dispatch(setStore({userInfo}));

            navigate(HOME);
        } catch (e) {
            // 处理不同类型的错误
            let errorMessage = e?.message || e?.msg || '注册失败，请重试';
            message.error(errorMessage);
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <div className={styles['container']}>
            <div className={styles['form-container']}>
                <h2>欢迎注册{WEB_NAME}</h2>
                <Form onFinish={onFinish} size="large" layout="vertical">
                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            { required: true, message: '请输入邮箱' },
                            {
                                validator: (_, value) => {
                                    if (value && !isRegEmail(value)) return Promise.reject('请输入正确邮箱');
                                    return Promise.resolve();
                                },
                            },
                        ]}
                    >
                        <Input prefix={<IconFont name="icon-email" />} placeholder="邮箱" />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input.Password prefix={<LockOutlined />} placeholder="密码" />
                    </Form.Item>

                    <Form.Item
                        name="rePassword"
                        label="确认密码"
                        dependencies={["password"]}
                        rules={[
                            { required: true, message: '请再次输入密码' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
                    </Form.Item>

                    <Button loading={submitting} type="primary" htmlType="submit" block>
                        注册
                    </Button>
                </Form>
            </div>
        </div>
    );
}
